package com.x.provider.customer.controller.rpc;

import com.x.core.utils.BeanUtil;
import com.x.core.web.api.R;
import com.x.core.web.controller.BaseRpcController;
import com.x.provider.api.customer.model.dto.directory.*;
import com.x.provider.api.customer.service.DirectoryRpcService;
import com.x.provider.customer.factory.dto.DirectoryDTOFactory;
import com.x.provider.customer.model.domain.directory.Attribute;
import com.x.provider.customer.model.domain.directory.AttributeValue;
import com.x.provider.customer.model.domain.directory.Region;
import com.x.provider.customer.service.directory.AttributeService;
import com.x.provider.customer.service.directory.RegionService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/rpc/directory")
public class DirectoryRpcController extends BaseRpcController implements DirectoryRpcService {

    private final AttributeService attributeService;
    private final DirectoryDTOFactory directoryDTOFactory;
    private final RegionService regionService;

    public DirectoryRpcController(AttributeService attributeService,
                                  DirectoryDTOFactory directoryDTOFactory,
                                  RegionService regionService){
        this.attributeService = attributeService;
        this.directoryDTOFactory = directoryDTOFactory;
        this.regionService = regionService;
    }

    @PostMapping("attribute/list")
    @Override
    public R<Map<String, AttributeDTO>> listAttribute(@RequestBody AttributeListReqDTO attributeListReqDTO) {
        List<Attribute> attributeList = attributeService.listAttribute().stream().filter(item -> CollectionUtils.isEmpty(attributeListReqDTO.getNameSystemList())
                || attributeListReqDTO.getNameSystemList().contains(item.getNameSystem())).collect(Collectors.toList());
        List<AttributeValue> attributeValueList = attributeService.listAttributeValue();

        return R.ok(directoryDTOFactory.prepare(attributeList, attributeValueList).stream().collect(Collectors.toMap(item -> item.getNameSystem(), item -> item)));
    }

    @PostMapping("region/list")
    @Override
    public R<List<RegionDTO>> listRegion(RegionListReqDTO regionListReqDTO) {
        List<Region> result = regionService.listRegion(regionListReqDTO.getCountryId(), regionListReqDTO.getLeLevel(), null);
        return R.ok(BeanUtil.prepare(result, RegionDTO.class));
    }

    @Override
    public R<List<AttributeDTO>> randomAttribute(AttributeRandomReqDTO attributeListReqDTO) {
        List<AttributeValue> result = attributeService.randomAttribute(attributeListReqDTO);
        return R.ok(BeanUtil.prepare(result, AttributeDTO.class));
    }
}
